﻿using System;
using System.Collections.Generic;
using AspectIntercept;
using GestorSQL.BLL.ImplementationsBridge;
using GestorSQL.BLL.QueryExecutions;
using GestorSQL.BusinessEntities;
using GestorSQL.DAO;
using GestorSQL.DAO.FileManager;
using GestorSQL.DAO.InterceptDAO;

namespace GestorSQL.BLL
{
    [Intercept(InterceptAllMethods = true, PreProcesor = typeof(DBTraceProcessor), PostProcesor = typeof(DBTraceProcessor), OmitMethods = new string[] { })]
    public class QueryManager : InterceptContext, IDisposable
    {
        #region Constantes
        public const int SUMMARYLENGTH = 100;
        #endregion

        #region Variables Privadas
        private IGestorSqlDao dao = new GestorSqlDao();
        private ConnectionManager _connectionManager = new ConnectionManager();
        private static BLLCommand bllCommand = null;
        private IFileManager fileManagerCompress = ImplementationBridge.GetFileManager("Compress");
        private IFileManager fileManagerText = ImplementationBridge.GetFileManager("Text");

        #endregion

        #region Metodos Publicos
        /// <summary>
        /// Obtiene los queries ejecutados por numero de caso
        /// </summary>
        /// <param name="caseNumber">Numero de Caso</param>
        /// <returns></returns>
        [InterceptOmit]
        public List<Query> GetQueriesByCase(string caseNumber)
        {
            return dao.GetQueriesByCase(caseNumber);
        }

        /// <summary>
        /// Obtiene el Query seleccionado
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="caseNumber"></param>
        /// <param name="queryId"></param>
        /// <returns></returns>
        [InterceptOmit]
        public string GetQueryStatement(string userName, string caseNumber, long queryId)
        {
            return fileManagerCompress.GetFileData(PathGetter.GetDevPath(new Caso() { UsuarioPruebas = userName, NumeroCaso = caseNumber }), string.Format(PathGetter.EJECUCION, queryId));

        }

        /// <summary>
        /// Ejecuta el query.
        /// </summary>
        /// <param name="caso"></param>
        /// <param name="query"></param>
        /// <returns>BLLReader</returns>
        public BLLReader ExecuteQuery(Caso caso, string query)
        {

            bllCommand = new BLLCommand(caso);

            return bllCommand.ExecuteQuery(query);


        }

        /// <summary>
        /// Guarda un Query que ha sido ejecutado
        /// </summary>
        /// <param name="bllReader">Lector de registros</param>
        /// <param name="caso">Caso</param>
        /// <param name="currentQuery">Sentencia Actual</param>
        public void SaveQueryExecution(BLLReader bllReader, Caso caso, string currentQuery, string comentarioEjecucion)
        {

            string _mensajeSalida = string.Empty;

            if (bllReader != null)
            {

                _mensajeSalida = bllReader.FinalMessage;

                if (!caso.IsProduction(caso.Historia.Estado_))
                {
                    string resumen = string.Format("{0}{1}", currentQuery.PadLeft(QueryManager.SUMMARYLENGTH, ' ').Substring(0, QueryManager.SUMMARYLENGTH).Trim(), (currentQuery.Length > QueryManager.SUMMARYLENGTH ? "..." : ""));
                    long idQuery = dao.SaveQuery(new Query { FK_Caso = caso.NumeroCaso, MensajeSalida = _mensajeSalida, Resumen = resumen, Satisfactorio = true });
                    fileManagerCompress.SaveFile(PathGetter.GetDevPath(caso), string.Format(PathGetter.EJECUCION, idQuery), currentQuery, true);
                }
                else
                {
                    long idLog = dao.SaveLog(new Log() { Fk_Solucion = caso.SolucionActual.Value, Satisfactorio = true , Comentario = comentarioEjecucion});
                    fileManagerText.SaveAppendFile(PathGetter.GetProdPath(caso, caso.SolucionActual.Value), PathGetter.SALIDA, string.Format("\n -- SALIDA RESULTADO EJECUCION -- ID LOG = {0} \n", idLog));
                    fileManagerText.SaveAppendFile(PathGetter.GetProdPath(caso, caso.SolucionActual.Value), PathGetter.FINAL, string.Format("\\* {0} *\\ \n {1}", comentarioEjecucion, currentQuery));
                }
            }


        }

        /// <summary>
        /// Guarda un comentario asociado a una sentencia previamente ejecutada
        /// </summary>
        /// <param name="idQuery">Id Sentencia</param>
        /// <param name="comment">Comentario</param>
        public void SaveQueryComment(long idQuery, string comment)
        {
            dao.SaveQueryComment(idQuery, comment);
        }
        #endregion

        #region IDisposable Members
        public void Dispose()
        {
            bllCommand.Dispose();
        }
        #endregion
    }
}
